<?php
// Include database connection
require_once __DIR__ . '/../config/database.php';

// Create database connection
try {
    $dsn = "mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHARSET;
    $conn = new PDO($dsn, DB_USERNAME, DB_PASSWORD);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("数据库连接失败: " . $e->getMessage());
}

// Include header
require_once 'includes/header.php';

// Get age group filter
$age_group = isset($_GET['age']) ? $_GET['age'] : '3-4';
$valid_ages = ['3-4', '5-6', '7-8', 'all'];
if (!in_array($age_group, $valid_ages)) {
    $age_group = '3-4';
}

// Handle actions
$message = '';
$message_type = '';

if (isset($_POST['action'])) {
    $action = $_POST['action'];
    
    switch ($action) {
        case 'update_module':
            $module_id = isset($_POST['module_id']) ? (int)$_POST['module_id'] : 0;
            $name = isset($_POST['name']) ? trim($_POST['name']) : '';
            $description = isset($_POST['description']) ? trim($_POST['description']) : '';
            $introduction = isset($_POST['introduction']) ? trim($_POST['introduction']) : '';
            $is_premium = isset($_POST['is_premium']) ? 1 : 0;
            $is_active = isset($_POST['is_active']) ? 1 : 0;
            
            if (empty($name)) {
                $message = '模块名称不能为空';
                $message_type = 'danger';
            } else {
                try {
                    $sql = "UPDATE km_cognitive_modules SET 
                            name = ?, description = ?, introduction = ?, 
                            is_premium = ?, is_active = ?, updated_at = NOW()
                            WHERE id = ?";
                    $stmt = $conn->prepare($sql);
                    $stmt->execute([$name, $description, $introduction, $is_premium, $is_active, $module_id]);
                    
                    if ($stmt->rowCount() > 0) {
                        $message = '模块已成功更新';
                        $message_type = 'success';
                    } else {
                        $message = '没有内容被更新';
                        $message_type = 'warning';
                    }
                } catch (Exception $e) {
                    $message = '数据库错误: ' . $e->getMessage();
                    $message_type = 'danger';
                }
            }
            break;
            
        // Additional actions would be added here
    }
}

// Get modules for the selected age group
try {
    $sql = "SELECT m.id, m.name, m.slug, m.description, m.is_premium, m.is_active, 
                  m.display_order, c.name as category_name
            FROM km_cognitive_modules m
            JOIN km_cognitive_categories c ON m.category_id = c.id
            WHERE c.age_group = ?
            ORDER BY m.display_order ASC";
    
    $stmt = $conn->prepare($sql);
    $stmt->execute([$age_group]);
    
    $modules = [];
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $modules[] = $row;
    }
} catch (Exception $e) {
    $message = '数据库错误: ' . $e->getMessage();
    $message_type = 'danger';
}
?>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">认知模块管理</h1>
    <div class="btn-toolbar mb-2 mb-md-0">
        <div class="btn-group me-2">
            <button type="button" class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#addModuleModal">
                <i class="bi bi-plus-lg"></i> 添加模块
            </button>
            <a href="items.php" class="btn btn-sm btn-outline-secondary">管理模块内容</a>
        </div>
    </div>
</div>

<?php if (!empty($message)): ?>
<div class="alert alert-<?php echo $message_type; ?> alert-dismissible fade show">
    <?php echo $message; ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php endif; ?>

<div class="card shadow mb-4">
    <div class="card-header py-3 d-flex justify-content-between align-items-center">
        <h6 class="m-0 font-weight-bold text-primary">认知模块列表</h6>
        <div class="btn-group">
            <?php foreach ($valid_ages as $age): ?>
            <a href="?age=<?php echo $age; ?>" class="btn btn-sm <?php echo $age == $age_group ? 'btn-primary' : 'btn-outline-primary'; ?>">
                <?php echo $age; ?>岁
            </a>
            <?php endforeach; ?>
        </div>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-bordered table-hover" width="100%" cellspacing="0">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>名称</th>
                        <th>标识符</th>
                        <th>描述</th>
                        <th>分类</th>
                        <th>高级</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($modules)): ?>
                    <tr>
                        <td colspan="8" class="text-center">暂无数据</td>
                    </tr>
                    <?php else: ?>
                        <?php foreach ($modules as $module): ?>
                        <tr>
                            <td><?php echo $module['id']; ?></td>
                            <td><?php echo htmlspecialchars($module['name']); ?></td>
                            <td><?php echo htmlspecialchars($module['slug']); ?></td>
                            <td class="text-truncate" style="max-width: 200px;">
                                <?php echo htmlspecialchars($module['description']); ?>
                            </td>
                            <td><?php echo htmlspecialchars($module['category_name']); ?></td>
                            <td>
                                <span class="badge <?php echo $module['is_premium'] ? 'bg-warning' : 'bg-secondary'; ?>">
                                    <?php echo $module['is_premium'] ? '是' : '否'; ?>
                                </span>
                            </td>
                            <td>
                                <span class="badge <?php echo $module['is_active'] ? 'bg-success' : 'bg-danger'; ?>">
                                    <?php echo $module['is_active'] ? '启用' : '禁用'; ?>
                                </span>
                            </td>
                            <td>
                                <button type="button" class="btn btn-sm btn-primary btn-edit-module" 
                                    data-id="<?php echo $module['id']; ?>"
                                    data-name="<?php echo htmlspecialchars($module['name']); ?>"
                                    data-description="<?php echo htmlspecialchars($module['description']); ?>"
                                    data-premium="<?php echo $module['is_premium']; ?>"
                                    data-active="<?php echo $module['is_active']; ?>"
                                    data-bs-toggle="modal" data-bs-target="#editModuleModal">
                                    <i class="bi bi-pencil"></i>
                                </button>
                                <a href="items.php?module=<?php echo $module['id']; ?>" class="btn btn-sm btn-info">
                                    <i class="bi bi-list-ul"></i>
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Edit Module Modal -->
<div class="modal fade" id="editModuleModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form method="post">
                <input type="hidden" name="action" value="update_module">
                <input type="hidden" name="module_id" id="edit_module_id">
                
                <div class="modal-header">
                    <h5 class="modal-title">编辑模块</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="edit_name" class="form-label">模块名称</label>
                        <input type="text" class="form-control" id="edit_name" name="name" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="edit_description" class="form-label">描述</label>
                        <textarea class="form-control" id="edit_description" name="description" rows="3"></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label for="edit_introduction" class="form-label">介绍内容</label>
                        <textarea class="form-control" id="edit_introduction" name="introduction" rows="5"></textarea>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-check mb-3">
                                <input class="form-check-input" type="checkbox" id="edit_is_premium" name="is_premium">
                                <label class="form-check-label" for="edit_is_premium">
                                    高级内容（需要付费）
                                </label>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-check mb-3">
                                <input class="form-check-input" type="checkbox" id="edit_is_active" name="is_active">
                                <label class="form-check-label" for="edit_is_active">
                                    启用
                                </label>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">保存更改</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Add Module Modal would be added here -->

<script>
$(document).ready(function() {
    // Edit module modal
    $('.btn-edit-module').on('click', function() {
        var id = $(this).data('id');
        var name = $(this).data('name');
        var description = $(this).data('description');
        var premium = $(this).data('premium');
        var active = $(this).data('active');
        
        $('#edit_module_id').val(id);
        $('#edit_name').val(name);
        $('#edit_description').val(description);
        $('#edit_is_premium').prop('checked', premium == 1);
        $('#edit_is_active').prop('checked', active == 1);
        
        // Get additional data via AJAX
        $.ajax({
            url: 'ajax/get_module.php',
            type: 'GET',
            data: {id: id},
            dataType: 'json',
            success: function(response) {
                if (response.status === 'success') {
                    $('#edit_introduction').val(response.data.introduction || '');
                }
            }
        });
    });
});
</script>

<?php
// Include footer
require_once 'includes/footer.php';
?> 